package remote

import (
	"errors"
	"log"
	"strings"

	"gitee.com/dark.H/go-remote-repl/datas"
	D "gitee.com/dark.H/go-remote-repl/datas"
)

func (m *ApiServerMan) Input(pre string, suggest ...string) (r string, err error) {
	if m == nil {
		return "", errors.New("NIL ApiServerMan err")
	}
	_, err = m.con.Write([]byte("repl:" + pre + SEP + strings.Join(suggest, ",")))
	if err != nil {
		log.Println("Send msg error:", err)
		return
	}
	buf := make([]byte, 4096)
	var n int
	n, err = m.con.Read(buf)
	if err != nil {
		log.Println("Repl Msg err:", err)
	}
	r = string(buf[:n])
	return
}

func (m *ApiServerMan) InputJson(pre string, suggests D.G) (r string, err error) {
	if m == nil {
		return "", errors.New("NIL ApiServerMan err")
	}
	r, err = datas.InputJson(m.con, pre, suggests)
	return
}

func (m *ApiServerMan) FunctionInput(key string, suggests D.G) (r string, err error) {
	if m == nil {
		return "", errors.New("NIL ApiServerMan err")
	}
	r, err = datas.FunctionJson(m.con, key, suggests)
	return
}

func (m *ApiServerMan) Choose(pre string, options ...string) (r string, err error) {
	if m == nil {
		return "", errors.New("NIL ApiServerMan err")
	}
	r, err = datas.Choose(m.con, pre, options...)
	return
}

func (m *ApiServerMan) Talk(repl bool, chooses ...string) (r string, err error) {
	if m == nil {
		return "", errors.New("NIL ApiServerMan err")
	}
	buf := make([]byte, 1024)
	var n int
	if !repl {

		_, err = m.con.Write([]byte("list:" + strings.Join(chooses, "\n")))
		if err != nil {
			log.Println("Send msg error:", err)
			return
		}
	} else {

		_, err = m.con.Write([]byte("repl:" + strings.Join(chooses, ",")))
		if err != nil {
			log.Println("Send msg error:", err)
			return
		}
	}
	n, err = m.con.Read(buf)
	if err != nil {
		log.Println("Repl Msg err:", err)
	}
	r = string(buf[:n])
	return
}

func (m *ApiServerMan) WhatToDo() (err error) {
	buf := make([]byte, 4)
	// m.con.SetReadDeadline(time.Now().Add(1))
	_, err = m.con.Read(buf)
	if err != nil {
		log.Println("Send msg error:", err)
		return
	}
	switch string(buf) {
	case "File":
		m.RecvFile()
		// return
	case "RIDE":
		if m.RidEFunc != nil && m.con != nil {
			m.RidEFunc(m.con)
		} else if DefaultRidEFunc != nil {
			DefaultRidEFunc(m.con)
		}
	case "menu":
		m.IntoMenu()
	default:
		m.FunctionDo()
	}
	return
}
